package com.eve.xstream;

import com.eve.xstream.node.Param;
import com.eve.xstream.node.Request;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author: ivan.yao<haif.yao@gmail.com>
 * @date: 17/6/17.
 */
public class ParamConvertor implements Converter {

    private static final Logger logger = LoggerFactory.getLogger(ParamConvertor.class);


    private static final String NAME_ATTR = "name";

    @Override
    public void marshal(Object o, HierarchicalStreamWriter writer, MarshallingContext context) {
        logger.info("marshal this object:{}" ,o);
    }

    @Override
    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
        Request request = new Request();
        if(reader.hasMoreChildren()) {
            while (reader.hasMoreChildren()) {
                reader.moveDown();
                final String name = reader.getAttribute(NAME_ATTR);
                Param param = new Param(name,reader.getValue());
                request.add(param);
                reader.moveUp();
            }
        }
        return request;
    }

    @Override
    public boolean canConvert(Class clazz) {
        return clazz.equals(Request.class);
    }
}
